package com.wenyl.juc.thread.shopTest;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Swimming Dragon
 * @description: TODO
 * @date 2024年11月07日 11:49
 */
public class Shop {
    private Semaphore semaphore;
    public Shop(int num){
        // 限流，每次5个线程
        semaphore = new Semaphore(num);
    }
    public void userShopping(String name){
        boolean flag = false;
        try {
            // 用户在1s内获取的许可
            flag = semaphore.tryAcquire(1, TimeUnit.SECONDS);
            Thread.sleep(2000);
            if(flag){
                System.out.println(name+",抢票成功,可以下单");
            }else{
                System.out.println(name+",抢票失败,请重试");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            semaphore.release();
        }
    }
}
